﻿
namespace CmdArgs.Validation.Options
{
    using System.Text.RegularExpressions;
    using CmdArgs.Settings;

    /// <summary>
    /// Validated the parameters against given regular expression.
    /// </summary>
    public sealed class RegexValidator : ValueValidatorTemplate
    {
        private Regex expression;

        /// <summary>
        /// Initializes a new instance of the <see cref="RegexValidator"/> class.
        /// </summary>
        /// <param name="expression">The expression for validation.</param>
        public RegexValidator(string expression)
        {
            this.expression = new Regex(expression);
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="RegexValidator"/> class.
        /// This constructor provides better performance because the expression is not parsed again.
        /// </summary>
        /// <param name="expression">The expression already parsed in Regex object.</param>
        public RegexValidator(Regex expression)
        {
            this.expression = expression;
        }

        protected override ValidationResult Validate(string value, OptionSettings optionSettings)
        {
            if (this.expression.IsMatch(value))
            {
                return ValidationResult.GetValidResult();
            }
            else
            {
                return new ValidationResult(
                    new ValidationError(
                        string.Format("Parameter value does not match pattern {0}", this.expression.ToString()), 
                        optionSettings));
            }
        }
    }
}
